import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/widgets/image/extended_image_ex.dart';

import 'widget_define_placeholder.dart';

class ImageView extends StatefulWidget {
  final String? imageUrl;
  final double? width;
  final double? height;
  final Color? backgroundColor;
  final BoxFit? fit;
  final Widget? placeholder;
  final double radius;
  final BorderRadius? borderRadius;
  final LoadStateChanged? loadStateHandler;
  final String? imageCacheName;
  final Color? color;
  final ExtendedImageMode mode;
  final DoubleTap? onDoubleTap;
  final InitGestureConfigHandler? initGestureConfigHandler;
  final int? cacheWidth;
  final int? cacheHeight;
  final int? maxBytes;
  final BoxBorder? border;
  final bool? enableSlideOutPage;
  final bool? openDefinePlaceholder;
  final bool clearMemoryCacheWhenDispose;
  final bool isNeedDecryption;
  final bool showFailReload;
  final AlignmentGeometry alignment;

  const ImageView({
    super.key,
    this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeholder,
    this.radius = 0.0,
    this.borderRadius,
    this.backgroundColor,
    this.loadStateHandler,
    this.imageCacheName,
    this.mode = ExtendedImageMode.none,
    this.onDoubleTap,
    this.color,
    this.initGestureConfigHandler,
    this.cacheWidth,
    this.cacheHeight,
    this.maxBytes,
    this.border,
    this.openDefinePlaceholder = false,
    this.enableSlideOutPage,
    this.clearMemoryCacheWhenDispose = true,
    this.isNeedDecryption = false,
    this.showFailReload = false,
    this.alignment = Alignment.center,
  });

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  @override
  Widget build(BuildContext context) {
    final isNullOrBlank = GetUtils.isNullOrBlank(widget.imageUrl) ?? true;
    final isUrl = GetUtils.isURL(widget.imageUrl ?? '');

    if (isNullOrBlank || !isUrl) {
      return placeholderOrBackground();
    }

    return buildImage();
  }

  Widget buildImage() {
    double buildWidth = widget.width ?? widget.radius * 2;
    double buildHeight = widget.height ?? widget.radius * 2;
    String imgUrl = widget.imageUrl?.split("?").first ?? "";
    imgUrl =
        imgUrl.startsWith('http') ? imgUrl : "${AppConfig.imageUrl}$imgUrl";
    String cacheKey = keyToMd5(imgUrl);
    return ExtendedImageEx.network(
      isNeedDecryption: widget.isNeedDecryption,
      cacheKey: cacheKey,
      widget.imageUrl ?? '',
      width: (buildWidth > 0) ? buildWidth : null,
      height: (buildHeight > 0) ? buildHeight : null,
      fit: widget.fit ?? BoxFit.cover,
      alignment: widget.alignment,
      cache: true,
      color: widget.color,
      enableSlideOutPage: widget.enableSlideOutPage ?? false,
      shape: BoxShape.rectangle,
      borderRadius: (widget.radius > 0)
          ? BorderRadius.circular(widget.radius)
          : widget.borderRadius,
      imageCacheName: widget.imageCacheName,
      onDoubleTap: widget.onDoubleTap,
      mode: widget.mode,
      initGestureConfigHandler: widget.initGestureConfigHandler,
      loadStateChanged: (state) {
        if (widget.loadStateHandler != null) {
          return widget.loadStateHandler?.call(state);
        } else {
          if (state.extendedImageLoadState == LoadState.failed) {
            return widget.showFailReload == true
                ? _buildImageLoadFail(state)
                : placeholderOrBackground();
          } else if (state.extendedImageLoadState == LoadState.loading) {
            return widget.placeholder ?? const DynamicPlaceholder();
          }
          return null;
        }
      },
      cacheWidth: widget.cacheWidth,
      cacheHeight: widget.cacheHeight,
      maxBytes: widget.maxBytes,
      border: widget.border,
      clearMemoryCacheWhenDispose: widget.clearMemoryCacheWhenDispose,
    );
  }

  Widget _buildImageLoadFail(ExtendedImageState state) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        height: 1.sw,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            WidgetDefinePlaceholder(
              width: widget.width,
              // height: widget.width,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '图片加载失败，点击重试',
                  style: TextStyle(
                    color: AppColor.hex('6F93BD'),
                    fontSize: 10.sp,
                  ),
                ),
                4.horizontalSpace,
                Icon(
                  Icons.refresh,
                  weight: 16.w,
                  color: AppColor.hex('6F93BD'),
                )
              ],
            ).marginOnly(top: 12.w)
          ],
        ),
      ),
      onTap: () {
        state.reLoadImage();
      },
    );
  }

  Widget placeholderOrBackground() {
    return widget.placeholder ??
        (widget.openDefinePlaceholder == true
            ? WidgetDefinePlaceholder(
                width: widget.width,
                height: widget.height,
                radius: widget.radius,
                backgroundColor: widget.backgroundColor,
              )
            : _background());
  }

  Widget _background() {
    return Container();
    // return StaticPlaceholder(
    //   radius: widget.radius,
    // );
  }

}
